package com.data.hijack.test;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author husq
 */
public class TemplateTestServer {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8688));
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> itera = selectionKeys.iterator();
            while (itera.hasNext()) {
                SelectionKey selectionKey = itera.next();
                itera.remove();
                if (selectionKey.isAcceptable()) {
                    ServerSocketChannel schannel = (ServerSocketChannel)selectionKey.channel();
                    SocketChannel socketChannel = schannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                } else if (selectionKey.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
                    ByteBuffer b = ByteBuffer.allocate(1024);
                    int len = socketChannel.read(b);
                    if (len < 0) {
                        System.out.println("通道已关闭: " + socketChannel);
                        socketChannel.close();
                    } else {
                        b.flip();
                        socketChannel.write(b);
                        socketChannel.register(selector, SelectionKey.OP_READ, b);
                    }

                }
            }
        }

    }

}
